package map;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * HashMap中有一个modCount 用于记录结构修改的次数（put，remove等，每次操作加一次），当遍历的时候先把modCount赋值给类变量，然后如果遍历过程中modCount的数量有了变化则会抛出ConcurrentModificationException异常。
 */
public class ForeachTest implements Runnable{
    private static Map<String,String> map = new HashMap<>();
    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newFixedThreadPool(1);
        service.execute(new ForeachTest());
        map.put("8","23");
        map.put("3","233");
        Thread.sleep(1000);
        map.put("5","233");
        map.remove("5","233");


    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        map.put("1","2");
        map.put("2","2");
        map.put("3","2");
        map.put("4","2");
        map.forEach((key,value)->{
            System.out.println(key);
            System.out.println(1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("完了");
    }
}
